package com.zcsy.manage.owner.controller.news;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.Globals;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.news.CellManual;
import com.zcsy.manage.model.news.NoticeInfo;
import com.zcsy.manage.model.news.NoticeRead;
import com.zcsy.manage.model.news.YellowPage;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.owner.service.common.IOCommonTokenService;
import com.zcsy.manage.owner.service.system.IOUserService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.news.ICellManualService;
import com.zcsy.manage.service.news.INoticeInfoService;
import com.zcsy.manage.service.news.INoticeReadService;
import com.zcsy.manage.service.news.IYellowPageService;
import com.zcsy.manage.service.system.IUserService;


/**
 * @Title: NewsController.java
 * @Package： com.hslt.manage.distribution.controller.news 
 * @Description: 
 * @author yangfan 373188993@qq.com
 * @Copyright: 2016 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月23日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */

@Controller
@RequestMapping(value= "info")
public class NewsController {
    
    @Autowired
    private INoticeInfoService noticeInfoService; 
	
    @Autowired
    private IOCommonTokenService commonTokenService;
    
    @Autowired
    private ICellManualService cellManualService;
    
    @Autowired
    private IYellowPageService yellowPageService;
    
	@Autowired
	private IUserService userService;
	
    @Autowired
    private ICellInfoService cellInfoService;
    
    @Autowired
    private IOUserService ouserService;
    
    @Autowired
    private INoticeReadService noticeReadService;
    
    /**
     * @Description 获取小区通知列表（包括平台消息通知）
     * @param cellId 小区id
     * @param token 
     * @return result小区通知列表
     * @author yangfan 373188993@qq.com
     * @date 2016年6月27日
     */
    @RequestMapping(value = "getCellNotice")
    @ResponseBody
    public RequestJson getNoticeInfo(String cellId, String token) {

        RequestJson result = new RequestJson();

        try {
        	String userId = "0";
        	if(!StringUtils.isEmpty(token) && !token.equals("null")){
        		CommonToken commonToken = commonTokenService.selectByToken(token);
                // 根据token查询登录名
                String loginname = commonToken.getAccount();
                // 根据登录名查询用户
                User user = ouserService.selectByLoginName(loginname);
                userId = user.getId();
        	}
            
            List<NoticeInfo> noticeList = noticeInfoService.getNoticeInfoList(cellId,userId);
            
            if(CollectionUtils.isNotEmpty(noticeList)){
                for (NoticeInfo item : noticeList) {
                    item.setWapUrl(OwnerConstants.WAP_URL + "/info/cellNoticeDetail?id=" + item.getId()+"&token="+ token);
//                    item.setWapUrl("http://127.0.0.1:8080/ownerConn/info/cellNoticeDetail?id=" + item.getId() +"&token="+ token);
                }
            }
            
            // 判断查询到的列表是否为空
            if (!noticeList.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.GET_INFOLIST_SUCCESS);
                result.setMsg("查看成功！");
                result.setObj(noticeList);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.GET_INFOLIST_FALSE);
                result.setMsg("无数据！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;
    }
    
	/**
	 * @Description 返回小区通知详情页面<br>
	 * 
	 * @param model
	 * @param id 小区通知id
	 * @return返回小区通知详情页面
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年7月10日
	 * @see 
	 */
	@RequestMapping(value = "cellNoticeDetail")
	public String cellNoticeDetail(Model model, String id,String token) {
		try {
			NoticeInfo noticeInfo = noticeInfoService.selectByPrimaryKey(id);
			if (noticeInfo != null) {
			    //统计多少人次阅读了该信息
			    String count = noticeReadService.selectCountPeople(id);
			    
			    if(!StringUtils.isEmpty(token) && !token.equals("null")){
			    	CommonToken commonToken = commonTokenService.selectByToken(token);
			        // 根据token查询登录名
			        String loginname = commonToken.getAccount();
			        // 根据登录名查询用户
			        User user = ouserService.selectByLoginName(loginname);
			        
			        NoticeRead noticeRead = new NoticeRead();
			        noticeRead.setUserId(user.getId());
			        noticeRead.setNoticeId(id);
			        
			        //查询已读表中是否已插入已读记录，未读则插入一条数据
			        if(noticeReadService.selectCountByUserId(noticeRead) == OwnerConstants.NOT_READ) {
			            //向已读表中插入一条数据
			            NoticeRead record = new NoticeRead();
			            
			            record.setId(UniqueNumberUtils.get18UniqueNumber());
			            record.setNoticeId(id);
			            record.setUserId(user.getId());
			            record.setUserType(user.getUserType());
			            record.setUserAccount(user.getLoginname());
			            noticeReadService.insert(record);
			        }
	            }
			    
		        
				model.addAttribute("noticeInfo", noticeInfo);
				model.addAttribute("count", count);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "news/cellNoticeDetail";
	}
    
    /**
     * @Description 获取社区政务列表
     * @param cellId 小区id
     * @param token 
     * @return result社区政务列表
     * @author yangfan 373188993@qq.com
     * @date 2016年6月24日
     */
    @RequestMapping(value = "getCellManual")
    @ResponseBody
    public RequestJson getCellManual (String cellId , String token) {
        
        RequestJson result = new RequestJson();
        
        try {
        	if(StringUtils.isEmpty(token) || token.equals("null")){
            	result.setSuccess(true);
            }else{
            	//调用方法传入token，无此token返回result为false
                commonTokenService.OrderInteractState(token , result);
            }
            
            if(result.isSuccess()){
                
                
                List<CellManual> cellManualList = cellManualService.getCellManuals(cellId);
                
                //将wap详情地址存放到对象中
                if(CollectionUtils.isNotEmpty(cellManualList)){
                    for (CellManual item : cellManualList) {
                        item.setWapUrl(OwnerConstants.WAP_URL + "/info/cellManualDetail?id="
                            + item.getId());
                        item.setLogo(Globals.getImageUrl() + item.getLogo());
                    }
                }
                if (!cellManualList.isEmpty()) {
                    result.setSuccess(true);
                    result.setResultCode(OwnerConstants.GET_CELLMANUAL_SUCCESS);
                    result.setMsg("查看成功！");
                    result.setObj(cellManualList);
                } else {
                    result.setSuccess(false);
                    result.setResultCode(OwnerConstants.GET_CELLMANUAL_FALSE);
                    result.setMsg("无数据！");
                }
                
            } else {
                result.setResultCode(OwnerConstants.GET_CELLMANUAL_FALSE);
                result.setMsg("网络异常 ！");
                result.setSuccess(false);
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        
        return result;
        
    }
    
    /**
     * @Description 获取便民黄页列表
     * @param cellId 小区id
     * @param pageName 黄页名称
     * @param phone 联系电话
     * @return result社区政务详情
     * @author yangfan 373188993@qq.com
     * @date 2016年6月23日
     */
    @RequestMapping(value = "getYellowPage")
    @ResponseBody
    public RequestJson getYellowPage(String searchKey,String cellId,Integer pNo) {
        
        RequestJson result = new RequestJson();
        
        try {
            // 指定默认为首页
            if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
                pNo = OwnerConstants.PAGE_NO;
            }
            YellowPage yellowPage = new YellowPage();
            
            //为yellow设置属性值
            yellowPage.setSearchKey(searchKey);
            yellowPage.setCellId(cellId);
            
            // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
            PageHelper.startPage(pNo, OwnerConstants.PAGE_SIZE);
            
            //通过关键字查询返回对象list
            List<YellowPage> yellowPageList =yellowPageService.selectBySearchKey(yellowPage);
            
            if (!yellowPageList.isEmpty()) {
                PageInfo<YellowPage> yellowPageListP = new PageInfo<YellowPage>(yellowPageList);
                result.setResultCode(OwnerConstants.GET_YELLOWPAGE_SUCCESS);
                result.setMsg("操作成功！");
                result.setSuccess(true);
                result.setObj(yellowPageListP);
            } else {
                result.setMsg("无数据！");
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.GET_YELLOWPAGE_FALSE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        return result;
    }
    
    
    /**
     * @Description 获取通知消息未读条数<br>
     * 
     * @param cellId 小区id
     * @param token token标示
     * @return 返回通知消息未读条数
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月5日
     * @see 
     */
    @RequestMapping(value = "getUnReadCount")
    @ResponseBody
    public RequestJson getUnReadCount (String cellId , String token) {
    	RequestJson result = new RequestJson();
        if(StringUtils.isEmpty(token) || token.equals("null")){
        	result.setResultCode(OwnerConstants.GET_USERINFO_SUCCESS);
    		result.setMsg("获取成功！");
    		result.setObj(0);
    		return result;
        }
        
        
        //调用方法传入token，无此token返回result为false
        result = commonTokenService.OrderInteractState(token , result);
        if(result.isSuccess()){
            
        	CommonToken tokenInfo = commonTokenService.selectByToken(token);
            String loginname = tokenInfo.getAccount();
            User user = userService.selectByPhone(loginname);
            
            CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
            
            //未读条数查询
            int unReadCount = OwnerConstants.INIT_UNREADCOUNT;
            if (cellInfo != null) {
            	unReadCount = noticeInfoService.selectUnreadCount(user.getId(), cellInfo.getId());
            	if(unReadCount != OwnerConstants.INIT_UNREADCOUNT){
            		result.setResultCode(OwnerConstants.GET_USERINFO_SUCCESS);
            		result.setMsg("获取成功！");
            		result.setObj(unReadCount);
            	}else{
            		result.setResultCode(OwnerConstants.GET_USERINFO_SUCCESS);
            		result.setMsg("无数据！");
            	}
			}
            
        } else {
            result.setResultCode(OwnerConstants.GET_CELLMANUAL_FALSE);
            result.setMsg("网络异常 ！");
            result.setSuccess(false);
        }
        
        return result;
        
    }    
    
	/**
	 * @Description 返回社区政务详情页面<br>
	 * 
	 * @param model
	 * @param id 社区政务id
	 * @return 返回社区政务详情页面
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年7月10日
	 * @see 
	 */
	@RequestMapping(value = "cellManualDetail")
	public String cellManualDetail(Model model, String id) {
		try {
			CellManual cellManual = cellManualService.selectByPrimaryKey(id);
			if (cellManual != null) {
				model.addAttribute("cellManual", cellManual);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "news/cellManualDetail";
	}
	
}
    

